# -- ChelloTraffic Widget --
#   data retriever script
#   by Gábor Sebestyén <segabor@chello.hu>, 2006
#   http://chellotraffic.uw.hu


require 'net/http'
require 'net/https'
require 'uri'


# parse traffic of current month
#
def process_current_month
  out = ""

  r = yield

  case r.body
	when /<strong>Hiba<\/strong>/
		out << "err:failed\n"
  when /^\s+Nincs\sadat\./
	  out <<  "0\n"
	when /([0-9\s]+)\sMB/
	  out <<  "#{$1.gsub(/\s/, "").to_i}\n"
	when /^\s+MB\s/
	  out <<  "0\n"
	else
		## $stderr.puts r.body
		out <<  "err:failed\n"
	end
	out
end




MNTH2N = %w(Jan Febr M&aacute;rc &Aacute;pr M&aacute;j J&uacute;n J&uacute;l Aug Szept Okt Nov Dec)


def process_months
	months = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	out = ""

	# get http response
	r = yield

	regex = /\<img\ssrc=\'images\/\d\.gif\'[^a]+alt\=\'([a-zA-Z&;]+):\s([0-9\s]+)\sMB\'\>/
	r.body.scan(regex) do
		months[MNTH2N.index($1)] = $2.gsub(/\s/, "").to_i
	end

  
	# produce
	months.inspect
end




exit(0) if ARGV.length < 2
http = Net::HTTP.new('traffic.bpcl.broadband.hu', 443)
http.use_ssl = true

r = http.post('/index.php', URI.escape("userName=#{ARGV[0]}&passWord=#{ARGV[1]}"))
c = r['set-cookie']
if c.nil?
	puts "err:login\n"
	exit(1)
end

response = ""

# get some data
# =============
#
# 1. actual month
response << process_current_month do
	http.get('/stat.php?type=cur', { "cookie" => c})
end

# 2. monthly traffic
response << process_months do
	http.get('/stat.php?type=mnt', { "cookie" => c})
end

# 3. daily traffic (...)

# logout
r = http.post('/index.php', URI.escape("logOut=1"), {"cookie" => c})

puts response

exit(0)
